package com.nd.android.u.ui.dataSupplier;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.database.Cursor;
import android.text.TextUtils;

import com.common.StarAppConfig;
import com.common.StarAppConst;
import com.nd.android.u.business.db.dao.AbstractChatDao;
import com.nd.android.u.business.db.dao.RecentContactRecords;
import com.nd.android.u.chatInterfaceImpl.ChatInterfaceImpl;
import com.nd.android.u.controller.ChatConst.LocalMessageType;
import com.nd.android.u.controller.bean.contact.RecentContactItem;
import com.nd.android.u.controller.bean.event.UnreadCountChangedEvent;
import com.nd.android.u.controller.factory.ChatDaoFactory;
import com.nd.android.u.controller.factory.ContactFactory;
import com.nd.android.u.controller.innerInterface.IDbOperation;
import com.nd.android.u.controller.innerInterface.IMessageDisplay;
import com.nd.android.u.controller.innerInterface.IUIDataSupplier;
import com.nd.android.u.ui.StarAppChatConst.MessageType;
import com.nd.android.u.ui.beanStarApp.AppContactItem;
import com.nd.android.u.ui.beanStarApp.DisplayMessage_App;
import com.product.android.business.config.Configuration;

import de.greenrobot.event.EventBus;

/**
 * 消息数据数据提供者
 * <br>Created 2014-9-20 上午10:36:19
 * @version  
 * @author   cb		
 * @see 	 
 */
public class AssistantDataSupplier implements IUIDataSupplier{
	
	/**数据库操作接口*/
    protected IDbOperation dbOperation;
    /**第一条消息的ID（时间上是最早的那一条）*/
    protected long firstMessageId;
    /**根据当前的id生成的数据展示接口*/
    protected IMessageDisplay displayMessage;
    
	public AssistantDataSupplier(){
		dbOperation=ChatDaoFactory.getInstance().get(LocalMessageType.APP);
		displayMessage=new DisplayMessage_App();
		displayMessage.setTypeId(AbstractChatDao.CONDITION_ALL);
		displayMessage.getProccessInterface().ackAllMessage();
	}
	
	@Override
	public List<IMessageDisplay> getData(long startId, int size) {
		ArrayList<IMessageDisplay> messages=new ArrayList<IMessageDisplay>();
		Cursor cursor=dbOperation.getEarlierMessage(displayMessage.getDbOperationSupport(), startId, size);
		if (cursor==null){
			return messages;
		}
		if (cursor.getCount()==0){
			cursor.close();
			return messages;
		}
		while (cursor.moveToNext()) {
            IMessageDisplay message = new DisplayMessage_App().getConcreteAppMessage(cursor);
            if (message == null) {
                continue;
            }

            // 判断是否是群类型的消息
            if (0 == ((DisplayMessage_App) message).appCode
                    .compareToIgnoreCase(StarAppConst.GROUP_HANDLE_EVENT_PERCODE)) {
                //如果是群消息
                if (StarAppConfig.getBooleanConfig(StarAppConfig.IS_OPEN_GROUP)) {
                    //如果群功能开放
                    message.getDbOperationSupport().parseFromCursor(cursor);
                    messages.add(message);
                }
            } else {
                message.getDbOperationSupport().parseFromCursor(cursor);
                messages.add(message);
            }
        }
		cursor.close();
		int count=messages.size();
		if (count>0){
			//取出来的消息是倒序排列，即最新的是在最前面，要反转一下
			Collections.reverse(messages);
			firstMessageId=messages.get(0).getMsgId();
			long currentTime = 0;
			for (int i=0;i<count;i++){
				IMessageDisplay message=messages.get(i);
				currentTime=message.setTimeString(currentTime);
				message.checkExtraFlag(i==count-1);
			}
		}
		return messages;
	}

	@Override
	public int getNewMessageCount() {
		return getUnreadMessageCount();
	}

	@Override
	public int getUnreadMessageCount() {
		// 获取未读消息数量
        RecentContactItem contactItem = ContactFactory.INSTANCE.getRecentContactItem(MessageType.ASSISTANT);
        contactItem=RecentContactRecords.INSTANCE.getItem(contactItem);
        // 当这个联系人是搜索出来的时候，取到的ITEM有可能是NULL
        if (contactItem != null) {
            return contactItem.getUnreadCount();
        }
        return 0;
	}

	@Override
	public long getFirstMessageId() {
		return firstMessageId;
	}

	@Override
	public void clearUnreadCount() {
		if (getUnreadMessageCount() > 0) {
			RecentContactItem contactItem = ContactFactory.INSTANCE.getRecentContactItem(MessageType.ASSISTANT);
			AppContactItem son=new AppContactItem();
			contactItem.setId(ChatInterfaceImpl.INSTANCE.parentChecker.getParentId(son));
            RecentContactRecords.INSTANCE.clearUnreadCount(contactItem);
            EventBus.getDefault().post(new UnreadCountChangedEvent());
        }
	}

	@Override
	public boolean isValidMessage(Object message) {
		if (!(message instanceof DisplayMessage_App)){
			return false;
		}
		
		String newAppId = StarAppConfig.getConfig(StarAppConfig.CONFIG_OAP_ID);
		if(TextUtils.isEmpty(newAppId)){
			newAppId = "0";
		}
		
		if (((DisplayMessage_App) message).appId == Configuration.STARAPPID
				|| ((DisplayMessage_App) message).appId == Integer.valueOf(newAppId)) {
			return true;
		}
		return false;
	}

	@Override
	public IMessageDisplay getConcreteMessage() {
		return new DisplayMessage_App();
	}

	@Override
	public long getId() {
		//这个方法在这里用不到
		return 0;
	}
}
